import express from 'express';
import session from 'express-session'
import mongoose from 'mongoose';
import dotenv from 'dotenv'
dotenv.config()
import routes from './api/routes';
import path from 'path';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import { de, zh_CN, Faker } from '@faker-js/faker';
import history from 'connect-history-api-fallback'

export const faker = new Faker({
    locale: [zh_CN, de]
})


const app = express();
app.set('trust proxy', true);

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 数据库连接
mongoose.connect(process.env.MONGODB_URI as string,
    {
        //@ts-ignore
        // useNewUrlParser: true,
        // useUnifiedTopology: true
    }
);

// 路由
app.use('/', routes);

// historyApiFallback配置
app.use(history());
app.use(history({
    rewrites: [
        {
            from: /^\/api\/.*$/,
            to: (context) => context.parsedUrl.pathname as string // 假设API请求不需要重写
        },
        {
            from: /\/[^\.]+$/,
            to: (context) => '/index.html' // 对于非文件请求，总是重定向到index.html
        }
    ]
}));

app.use(express.urlencoded({ extended: true, limit: '10000kb' }))
app.use(express.json({ limit: '10000kb' }))

// 配置静态文件服务
// app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use('/uploads', express.static('uploads'));
app.use('/mp', express.static('mp'));
app.use(cors({
    credentials: true
}))

app.use(cookieParser())

app.use(session({
    secret: 'cgc',
    resave: false,
    saveUninitialized: true,
    // cookie: { secure: true }
}));


export default app;
